package com.cly.service.impl;

import com.cly.base.contants.CacheKeysConstants;
import com.cly.entity.Course;
import com.cly.entity.Subject;
import com.cly.mapper.CourseMapper;
import com.cly.result.JsonRequest;
import com.cly.result.exenum.RequestException;
import com.cly.service.ICourseStatisticsService;
import com.cly.service.ISubjectService;
import com.cly.statistics.PieStatistics;
import com.cly.statistics.SumStatistics;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 课程统计服务实现类
 *
 * @author by 春风能解释
 * <p>
 * 2024/10/15
 */
@Service
@RequiredArgsConstructor
public class CourseStatisticsServiceImpl implements ICourseStatisticsService {


    /**
     * 课程服务
     */
    private final CourseMapper courseMapper;

    /**
     * 科目服务
     */
    private final ISubjectService subjectService;

    /**
     * 课程总数统计
     *
     * @return 课程总数
     */
    @Override
    @Cacheable(value = CacheKeysConstants.CourseKeys.COURSE_COUNT)
    public JsonRequest<List<SumStatistics<Long>>> sumStatisticsCourse() {
        return JsonRequest.success(courseMapper.sumStatisticsCourse());
    }

    /**
     * 课程类型统计
     *
     * @return 课程类型
     */
    @Override
    @Cacheable(value = CacheKeysConstants.CourseKeys.COURSE_TYPE)
    public JsonRequest<List<PieStatistics<Long>>> sumStatisticsCourseType() {
        List<Course> courses = courseMapper.selectList(null);
        List<Long> ids = courses.stream()
                .map(Course::getSubjectId)
                .toList();
        JsonRequest<Map<Long, Subject>> subjectJson = subjectService.lookSubjectMap(ids);
        if (!subjectJson.getSuccess()) {
            return JsonRequest.error(RequestException.NOT_FOUND);
        }
        Map<Long, Subject> subjectMap = subjectJson.getData();
        Map<String, PieStatistics<Long>> map = new HashMap<>();
        for (Course course : courses) {
            Long subjectId = course.getSubjectId();
            PieStatistics<Long> pieStatistics = map.get(subjectMap.get(subjectId).getName());
            if (Objects.isNull(pieStatistics)) {
                map.put(subjectMap.get(subjectId).getName(),
                        new PieStatistics<Long>()
                                .setName(subjectMap.get(subjectId).getName())
                                .setValue(1L));
            } else {
                map.put(subjectMap.get(subjectId).getName(), pieStatistics
                        .setValue(pieStatistics.getValue() + 1L));
            }
        }
        return JsonRequest.success(new ArrayList<>(map.values()));
    }
}
